package com.mashibing.juc.c_022_RefTypeAndThreadLocal;


import com.sun.org.apache.bcel.internal.generic.NEW;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.LinkedList;
import java.util.List;

/**
 * 虚引用
 * 用于写虚拟机JVM
 * 堆外内存有unsafe回收，unsafe在1.8中可以通过反射使用
 * @author: Yuanzt
 * @Date: 2021/3/31
 */
public class T04_PhantomReference {

    private static final List<Object> LIST = new LinkedList<>();
    //队列
    private static final ReferenceQueue<M> QUEUE = new ReferenceQueue<>();

    public static void main(String[] args) {
        //虚引用，只要有垃圾回收，就会立刻被回收。
        PhantomReference<M> phantomReference = new PhantomReference<>(new M(),QUEUE);
        new Thread(()->{
            while (true){
                LIST.add(new byte[1024*1024]);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(phantomReference.get());
            }
        }).start();

        //监测队列，监测虚引用是否被回收
        new Thread(()->{
            while (true){
                Reference<? extends M> poll = QUEUE.poll();
                if (poll != null)
                    System.out.println("-----虚引用对象被JVM回收了-----" + poll);
            }
        }).start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
